import React, { useState } from 'react';
import style from './index.less';
import { Modal, Button, Steps, Form, Spin } from 'antd';
import { useSetState, useMount } from 'ahooks';

// components
import { TRMessage } from '@/components';
import TRNotification from '@/utils/notification';
import { CloseOutlined } from '@/utils/antdIcons';
import { addApplication, updateApplication, getApplicationAllInfo } from '@/services/power';
import { HttpCode } from '@/utils/contacts';
import BasicInformation from './components/BasicInformation'; // 基础信息
import AMenuCompontent from './components/AMenuCompontent'; // 一级菜单
import SecondaryMenu from './components/SecondaryMenu'; // 二级菜单
import AssigningRoles from './components/AssigningRoles'; // 分配角色
import { STEP_lIST, STEP, MODEL_TITLTE } from './helper.js';
import Alert from '#/components/Alert';

const { Step } = Steps;

const AppMessageModal = ({ onPress, modelType, detailId, defaultFlag, updateAppAuthority }) => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false); // modal
  const [current, setCurrent] = useState(0); // 步骤进度
  const [loading, setLoading] = useState(false);
  const [state, setState] = useSetState({
    firstMenuListModel: [],
    applicationName: '',
    applicationNote: '',
    roleListModel: [],
    customApplicationId: '',
  });

  useMount(() => {
    setVisible(true);
    if (modelType === 'edit') _handleEdit();
  });

  const _handleEdit = async () => {
    setLoading(true);
    const res = await getApplicationAllInfo(detailId);
    setLoading(false);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const dataRole = [...(res?.data?.roleList || [])];
      if (!defaultFlag) {
        dataRole.forEach((item) => (item.saasAdminFlag = false));
      }
      setState({
        firstMenuListModel: res.data.firstMenuList,
        applicationName: res.data.name,
        applicationNote: res.data.applicationExplain,
        roleListModel: dataRole,
        customApplicationId: res.data.customApplicationId,
      });
    } else {
      TRMessage.error(res.message || '请求失败，请稍后再试');
      onPress({ index: 0 });
      setVisible(false);
    }
  };

  const isEdit = () => {
    const { applicationName, applicationNote } = form.getFieldsValue([
      'applicationName',
      'applicationNote',
    ]);
    if (modelType === 'add') {
      const isEdit = [...Object.values(state), applicationName, applicationNote].find(
        (v) => !_.isEmpty(v),
      );
      if (!isEdit) return true;
    } else if (modelType === 'edit') {
      const newState = { ...state };
      newState.applicationName = applicationName;
      newState.applicationNote = applicationNote;
      return false;
    }
  };

  const _onCancel = async () => {
    if (isEdit()) {
      onPress({ index: 0 });
      setVisible(false);
      return;
    }
    let res = await Alert.show('当前工作将不被保存，继续执行此操作？', document.body);
    if (res.index === 1) {
      onPress({ index: 0 });
      setVisible(false);
    }
  };

  const _onOk = async () => {
    if (!updateAppAuthority) return TRMessage.info('请联系管理员获取相关权限');
    const params = {
      applicationExplain: state.applicationNote,
      firstMenuList: state.firstMenuListModel,
      name: state.applicationName,
      customApplicationId: state.customApplicationId,
      roleList: state.roleListModel,
    };
    if (!params.name) return TRMessage.error('应用名称不能为空');
    const findAMenu = _.find(state.firstMenuListModel, (_v) => {
      if (_v.name && _v.operationType !== 3) return _v;
    });
    if (!findAMenu) return TRMessage.error(`一级菜单不能为空`);
    const findSec = _.find(state.firstMenuListModel, (_f) => {
      const arr = _.filter(_f.secondMenuList, (_v) => _v.operationType !== 3);
      return !_.isEmpty(arr);
    });
    if (!findSec) return TRMessage.error(`二级菜单不能为空`);
    if (!params?.roleList?.length) return TRMessage.error('角色不能为空');
    switch (modelType) {
      case 'add':
        setLoading(true);
        const resAdd = await addApplication(params);
        setLoading(false);
        if (resAdd?.statusCode === HttpCode.SUCCESS) {
          TRMessage.success('添加成功');
          onPress({ index: 0, success: true });
          setVisible(false);
        } else {
          TRMessage.error(resAdd?.message || '数据有误，请稍后再试！');
        }
        break;
      case 'edit':
        setLoading(true);
        const resUpdate = await updateApplication(params);
        setLoading(false);
        if (resUpdate?.statusCode === HttpCode.SUCCESS) {
          TRMessage.success('修改成功');
          onPress({ index: 0, success: true });
          setVisible(false);
        } else {
          TRMessage.error(resUpdate?.message || '数据有误，请稍后再试！');
        }
        break;
    }
  };

  const _jumpStep = async (step) => {
    if (step === 1 && current === 0) {
      const values = await form.validateFields();
      const { applicationName, applicationNote } = values;
      const name = applicationName.trim();
      if (!name) return TRMessage.error(`应用名称不能为空`);
      setState({
        applicationName,
        applicationNote,
      });
    }
    if (step === 1 && current === 1) {
      const findAMenu = _.find(state.firstMenuListModel, (_v) => {
        if (_v.name && _v.operationType !== 3) return _v;
      });
      if (!findAMenu) return TRMessage.error(`一级菜单不能为空`), setCurrent(1);
    }
    if (step === 1 && current === 2) {
      const findSec = _.find(state.firstMenuListModel, (_f) => {
        const arr = _.filter(_f.secondMenuList, (_v) => _v.operationType !== 3);
        return !_.isEmpty(arr);
      });
      if (!findSec) return TRMessage.error(`二级菜单不能为空`);
    }
    setCurrent(current + step);
  };

  const _onChangeSteps = (step) => {
    if (step === 2) {
      const findAMenu = _.find(state.firstMenuListModel, (_v) => {
        if (_v.name && _v.operationType !== 3) return _v;
      });
      if (!findAMenu) return TRMessage.error(`一级菜单不能为空`), setCurrent(1);
    }
    if (current === 2 && step === 3) {
      const findSec = _.find(state.firstMenuListModel, (_f) => {
        const arr = _.filter(_f.secondMenuList, (_v) => _v.operationType !== 3);
        return !_.isEmpty(arr);
      });
      if (!findSec) return TRMessage.error(`二级菜单不能为空`);
    }
    const values = form.getFieldsValue(['applicationName', 'applicationNote']);
    setState({
      applicationName: values?.applicationName || '',
      applicationNote: values?.applicationNote || '',
    });
    setCurrent(step);
  };

  const _footerRender = (type) => {
    switch (type) {
      case 0:
        return (
          <>
            <Button key="cancel" onClick={_onCancel}>
              取消
            </Button>
            <Button key="next" type="primary" onClick={() => _jumpStep(STEP['next'])}>
              下一步
            </Button>
          </>
        );
      case 3:
        return (
          <>
            <Button key="previous" onClick={() => _jumpStep(STEP['previous'])}>
              上一步
            </Button>
            <Button
              key="finish"
              type="primary"
              onClick={_onOk}
              style={{
                borderColor: updateAppAuthority ? 'var(--bd-primary)' : 'var(--bd)',
                background: updateAppAuthority ? 'var(--base2)' : 'var(--bg-form)',
                color: updateAppAuthority ? 'var(--font-active)' : 'var(--font3)',
              }}
            >
              完成
            </Button>
          </>
        );
      default:
        return (
          <>
            <Button key="previous" onClick={() => _jumpStep(STEP['previous'])}>
              上一步
            </Button>
            <Button key="next" type="primary" onClick={() => _jumpStep(STEP['next'])}>
              下一步
            </Button>
          </>
        );
    }
  };

  // 一级菜单回显
  const echoApp = (list) => {
    let i = 0;
    const _data = _.map(list, (_v) => {
      if (_v.operationType !== 3) {
        _v.sort = i;
        i = i + 1;
      } else {
        _v.sort = -1;
      }
      return _v;
    });
    setState({
      firstMenuListModel: _data,
    });
  };

  // 角色回显
  const echoRoles = (list) => {
    setState({
      roleListModel: list,
    });
  };

  const _renderStep = () => {
    switch (current) {
      case 0:
        return (
          <BasicInformation
            form={form}
            modelType={modelType}
            firstMenuListModel={state.firstMenuListModel}
            applicationName={state.applicationName}
            applicationNote={state.applicationNote}
            defaultFlag={defaultFlag}
          />
        );
      case 1:
        return (
          <AMenuCompontent
            form={form}
            modelType={modelType}
            firstMenuListModel={state.firstMenuListModel}
            echoApp={echoApp}
            defaultFlag={defaultFlag}
          />
        );
      case 2:
        return (
          <SecondaryMenu
            form={form}
            modelType={modelType}
            firstMenuListModel={state.firstMenuListModel}
            echoApp={echoApp}
            defaultFlag={defaultFlag}
          />
        );
      case 3:
        return (
          <AssigningRoles
            form={form}
            modelType={modelType}
            roleListModel={state.roleListModel}
            echoRoles={echoRoles}
            defaultFlag={defaultFlag}
          />
        );
      default:
        return null;
    }
  };

  return (
    <Modal
      centered={true}
      visible={visible}
      onCancel={_onCancel}
      footer={false}
      maskClosable={false}
      width={700}
      title={MODEL_TITLTE[modelType]}
      size="small"
      bodyStyle={{ padding: '10px 20px 20px', height: '568px', position: 'relative' }}
      wrapClassName={style.modalStyle}
      closeIcon={<CloseOutlined style={{ fontSize: 16 }} />}
    >
      <Spin spinning={loading}>
        <Steps
          current={current}
          responsive={false}
          status="process"
          type="navigation"
          size="small"
          className={style.navigationSteps}
          onChange={modelType !== 'add' ? _onChangeSteps : null}
        >
          {STEP_lIST &&
            STEP_lIST.map((_step, index) => {
              return (
                <Step
                  key={index}
                  title={_step.title}
                  status={index === current ? process : _step.status}
                />
              );
            })}
        </Steps>
        <div style={{ paddingTop: '15px' }}>{_renderStep()}</div>
        <div className={style.modelFooter}>{_footerRender(current)}</div>
      </Spin>
    </Modal>
  );
};

class SettleModal {
  __key__ = '';
  show = ({ modelType, detailId, defaultFlag, updateAppAuthority }) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <AppMessageModal
            onPress={(obj) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(obj);
            }}
            modelType={modelType}
            detailId={detailId}
            defaultFlag={defaultFlag}
            updateAppAuthority={updateAppAuthority}
          />
        ),
        dismiss: this.dismiss,
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

const TRSettleModal = new SettleModal();
export default TRSettleModal;
